package com.szq.yygh.hosp.controller.api;

import com.szq.yygh.common.exception.YyghException;
import com.szq.yygh.common.helper.HttpRequestHelper;
import com.szq.yygh.common.result.ResultCodeEnum;
import com.szq.yygh.hosp.service.HospitalSetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/***
 * All rights Reserved, Designed By www.jx-lab.com
 * @Title: BaseController
 * @Description:
 * @author lixy
 * @date 2021/8/19 17:39
 * @version V1.0
 * @Copyright: www.jx-lab.com Inc. All rights reserved.
 * 注意：本内容仅限于众合景轩信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@RestController
public class BaseController {

    @Autowired
    private HospitalSetService hospitalSetService;

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    protected Map<String, Object> getRequestMap(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> requestMap = HttpRequestHelper.switchMap(parameterMap);
        //校验签名是否正确
        if (!checkSignIsOk(requestMap)){
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        return requestMap;
    }

    /**
     * 校验签名是否正确
     * @param requestMap
     * @return
     */
    protected boolean checkSignIsOk(Map<String, Object> requestMap){
        boolean flag = true;
        String hoscode = (String) requestMap.get("hoscode");
        if(StringUtils.isEmpty(hoscode)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //传输过程中“+”转换为了“ ”，因此我们要转换回来
        String logoDataString = (String)requestMap.get("logoData");
        if(!StringUtils.isEmpty(logoDataString)) {
            String logoData = logoDataString.replaceAll(" ", "+");
            requestMap.put("logoData", logoData);
        }
        String signKey = hospitalSetService.findSignKey(hoscode);
        if (!HttpRequestHelper.isSignEquals(requestMap, signKey)){
            flag = false;
        }

        return flag;
    }
}
